package org.cocos2dx.javascript;

import android.support.annotation.NonNull;
import android.util.Log;

import com.google.android.play.core.review.ReviewInfo;
import com.google.android.play.core.review.ReviewManager;
import com.google.android.play.core.review.ReviewManagerFactory;
import com.google.android.play.core.tasks.OnCompleteListener;
import com.google.android.play.core.tasks.Task;

public class ReviewMgr {
    private static final String TAG = "ReviewMgr";

    private static InstantAppActivity this_tmp;
    private static ReviewManager reviewManager;
    private static ReviewMgr mInstance = null;

    public static ReviewMgr getInstance() {
        if (null == mInstance) {
            mInstance = new ReviewMgr();
        }
        return mInstance;
    }

    public void init(InstantAppActivity context) {
        Log.d(TAG, "init");
        this.this_tmp = context;

        reviewManager = ReviewManagerFactory.create(context);
    }

    private static void showReview() {
        Task<ReviewInfo> request = reviewManager.requestReviewFlow();
        request.addOnCompleteListener(new OnCompleteListener<ReviewInfo>() {
            @Override
            public void onComplete(@NonNull Task<ReviewInfo> task) {
                if (task.isSuccessful()) {
                    // We can get the ReviewInfo object
                    Log.d(TAG, "We can get the ReviewInfo object");
                    Task<Void> flow = reviewManager.launchReviewFlow(this_tmp, task.getResult());
                    flow.addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            // The flow has finished. The API does not indicate whether the user
                            // reviewed or not, or even whether the review dialog was shown. Thus, no
                            // matter the result, we continue our app flow.
                            Log.d(TAG, "showReview.onComplete");
                        }
                    });
                } else {
                    // There was some problem, continue regardless of the result.
                    Log.d(TAG, "There was some problem, continue regardless of the result." + task);
                }
            }
        });
    }
}
